#region license
/*
 * Copyright (C) 2007 CchenSoft.com
 * 
 * This library is free software; you can redistribute it and/or modify it 
 * under the terms of the GNU Lesser General Public License 2.1 or later, as
 * published by the Free Software Foundation. See the included License.txt
 * or http://www.gnu.org/copyleft/lesser.html for details.
 * 
 * Author: Billy Zhang
 */
#endregion

using System;
using System.Collections.Generic;
using System.Text;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.ComponentModel;
using System.Web.UI.Design;
using CchenSoft.Portal.Cfg;
using CchenSoft.Portal.Registry;
using CchenSoft.Portal.Spi.Plugin;
using CchenSoft.Portal.Spi.Registry;

namespace CchenSoft.Portal.Web.UI
{
    [Designer(typeof(HtmlControlDesigner))]
    [ParseChildren(true)]
    public class Editor : Control, INamingContainer, IPluginSupport
    {        
        private string pluginName;
        private IEditorPlugin plugin;
        private string content;

        public IPlugin GetPlugin()
        {
            if (plugin == null)
            {
                if (!string.IsNullOrEmpty(pluginName))
                    plugin = (IEditorPlugin)PluginRegistry.Instance.GetPlugin(pluginName);

                if (plugin == null)
                {
                    plugin = (IEditorPlugin)PluginRegistry.Instance.GetPluginByCategory("editor");
                }
            }
            return plugin;
        }

        protected override void CreateChildControls()
        {
            plugin = (IEditorPlugin)GetPlugin();
            Control editor = this.LoadEditor();
            this.InitializeEditor(editor);
            this.Controls.Add(editor);
        }

        protected virtual void InitializeEditor(Control editor)
        {
            plugin.Initialize(editor);
            plugin.Content = content;
        }

        public string PluginName
        {
            get { return pluginName; }
            set { pluginName = value; }
        }

        public string Content
        {
            get { return plugin.Content; }
            set { content = value; }
        }

        protected virtual Control LoadEditor()
        {
            return plugin.LoadEditor(this.Page);
        }
    }
}
